package com.tencent.wepay.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SignUtil {
	private static Logger logger=LoggerFactory.getLogger(SignUtil.class);
	public enum SignType{
		MD5;
	}
	public static String md5(String data) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(data.getBytes());
			byte b[] = md.digest();
			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			// 32位加密
			return buf.toString();
			// 16位的加密
			// return buf.toString().substring(8, 24);
		} catch (NoSuchAlgorithmException e) {
			logger.error("no such md5 algorithm", e);
			return null;
		}

	}
	public static String toSign(Map<String,Object> map,String key){
		StringBuffer str=new StringBuffer();
		for(Entry<String, Object> entry:map.entrySet()){
            if(entry.getValue()!=null){
            	str.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
		str.append("key="+key);
		return SignUtil.md5(str.toString());
	}
}
